'use strict';

const RouterService = require('../base');
const {
  OrderStatusEnum,
  CommonUserLevelEnum,
  BalanceLogTypeEnum
} = require("../../utils/enum");
class OrderCodeService extends RouterService {
  static get modelName() {
    return 'Business.OrderCode';
  }
  async distribute(orderCode, transaction){
    // 4.1 获取用户，查询该用户是否有上级
    const user = await this.ctx.model.Business.User.findOne({
      where: {
        id: orderCode.user_id
      },
      include: [
        {
          model: this.ctx.model.Business.User,
          as: 'parent',
        }
      ],
      transaction
    })
    /**
     * 分佣金
     * 1. 抽佣金，是根据当前orderCode中的分配比例来分佣，需要计算出佣金金额
     * 分成逻辑：商家70-rebate_price_shop、平台20-rebate_price_platform、一级5-rebate_price_agent、二级5-rebate_price_agent2
     * 1. 商家（分配给该订单核销的shop_user_id）、平台固定分配（平台账号固定id=1）
     * 1. 如果普通用户购买，按按上述示例分配
     * 2. 如果非最底层购买，上方任意一级购买则当前购买人获取下一级的金额
     * 3. user_type 0 平台管理员 1 普通用户 2 商家 3 一级分销商 4 二级分销商
     * 4. 如果上级用户是普通用户，那么执行返现逻辑rebate_price或者上级用户是空，商家、平台正常分佣，平台获取剩余部分-rebate_price
     */
    const balanceList = []
    const defaultParams = {
      order_id: orderCode.order_id,
      order_item_id: orderCode.order_item_id,
      order_code_id: orderCode.id,
      product_name: `${orderCode.product_name}【¥${orderCode.product_price}】`,
    }
    // 商家正常分佣
    balanceList.push({
      ...defaultParams,
      user_id: orderCode.shop_user_id,
      user_type: CommonUserLevelEnum.SHOP_USER,
      amount: orderCode.rebate_price_shop,
      type: BalanceLogTypeEnum.DISTRIBUTOR_INCOME,
      description: `订单${orderCode.order_no}的商家佣金【${orderCode.rebate_price_shop_percent}%】`
    })
    // 平台
    balanceList.push({
      ...defaultParams,
      user_id: 1,
      user_type: CommonUserLevelEnum.ADMIN,
      amount: orderCode.rebate_price_platform,
      type: BalanceLogTypeEnum.DISTRIBUTOR_INCOME,
      description: `订单${orderCode.order_no}的平台佣金【${orderCode.rebate_price_platform_percent}%】`
    })
    // 存在上级
    if (user.parent_user_id) {
      // 判断上级类型
      // 1. 自己普通用户-上级普通用户，获取下一级的佣金, 平台获取一级、二级佣金、减去普通用户的返佣金
      if (user.user_type === CommonUserLevelEnum.NORMAL_USER && user.parent.user_type === CommonUserLevelEnum.NORMAL_USER) {
        balanceList.push({
          ...defaultParams,
          user_id: 1,
          user_type: CommonUserLevelEnum.ADMIN,
          amount: orderCode.rebate_price_agent,
          type: BalanceLogTypeEnum.DISTRIBUTOR_INCOME,
          description: `订单${orderCode.order_no}的一级分销商佣金【${orderCode.rebate_price_agent_percent}%】`
        })
        balanceList.push({
          ...defaultParams,
          user_id: 1,
          user_type: CommonUserLevelEnum.ADMIN,
          amount: orderCode.rebate_price_agent2,
          type: BalanceLogTypeEnum.DISTRIBUTOR_INCOME,
          description: `订单${orderCode.order_no}的二级分销商佣金【${orderCode.rebate_price_agent_percent2}%】`
        })
        if (Number(orderCode.rebate_price)) {
          // 上级用户获得佣金
          balanceList.push({
           ...defaultParams,
            user_id: user.parent_user_id,
            user_type: CommonUserLevelEnum.NORMAL_USER,
            amount: Number(orderCode.rebate_price),
            type: BalanceLogTypeEnum.DISTRIBUTOR_INCOME,
            description: `订单${orderCode.order_no}的返佣金`
          })
          // 平台扣减返佣金
          balanceList.push({
          ...defaultParams,
            user_id: 1,
            user_type: CommonUserLevelEnum.ADMIN,
            amount: -Number(orderCode.rebate_price),
            type: BalanceLogTypeEnum.DISTRIBUTOR_INCOME,
            description: `订单${orderCode.order_no}扣减普通用户返佣金`
          })
        }
      }
      // 2. 自己普通用户 - 上级二级分销商，
      else if (user.user_type === CommonUserLevelEnum.NORMAL_USER && user.parent.user_type === CommonUserLevelEnum.TWO_LEVEL_DISTRIBUTOR) {
        // 二级分佣
        balanceList.push({
         ...defaultParams,
          user_id: user.parent_user_id,
          user_type: CommonUserLevelEnum.TWO_LEVEL_DISTRIBUTOR,
          amount: orderCode.rebate_price_agent2,
          type: BalanceLogTypeEnum.DISTRIBUTOR_INCOME,
          description: `订单${orderCode.order_no}的二级分销商佣金【${orderCode.rebate_price_agent_percent2}%】`
        })
        // 一级分佣
        // 查找一级用户
        console.log('user',user.parent)
        const level1User = await this.ctx.model.Business.User.findOne({
          where: {
            id: user.parent.parent_user_id
          },
          transaction
        })
        if (level1User) {
          balanceList.push({
          ...defaultParams,
            user_id: level1User.id,
            user_type: CommonUserLevelEnum.ONE_LEVEL_DISTRIBUTOR,
            amount: orderCode.rebate_price_agent,
            type: BalanceLogTypeEnum.DISTRIBUTOR_INCOME,
            description: `订单${orderCode.order_no}的一级分销商佣金【${orderCode.rebate_price_agent_percent}%】`
          })
        }
      }
      // 3. 自己二级分销商 - 上级一级分销商
      else if (user.user_type === CommonUserLevelEnum.TWO_LEVEL_DISTRIBUTOR && user.parent.user_type === CommonUserLevelEnum.ONE_LEVEL_DISTRIBUTOR) {
        // 上级时一级分销商，即二级分销商自己购买，
        // 一级获取自己本身的佣金
        balanceList.push({
         ...defaultParams,
          user_id: user.parent_user_id,
          user_type: CommonUserLevelEnum.ONE_LEVEL_DISTRIBUTOR,
          amount: orderCode.rebate_price_agent,
          type: BalanceLogTypeEnum.DISTRIBUTOR_INCOME,
          description: `订单${orderCode.order_no}的一级分销商佣金【${orderCode.rebate_price_agent_percent}%】`
        })
        // 自己再获取二级的佣金
        balanceList.push({
        ...defaultParams,
          user_id: user.id,
          user_type: CommonUserLevelEnum.TWO_LEVEL_DISTRIBUTOR,
          amount: orderCode.rebate_price_agent2,
          type: BalanceLogTypeEnum.DISTRIBUTOR_INCOME,
          description: `订单${orderCode.order_no}的二级分销商佣金【${orderCode.rebate_price_agent_percent2}%】`
        })
      }
      // 4. 自己是一级 - 上级空
      else if (user.user_type === CommonUserLevelEnum.ONE_LEVEL_DISTRIBUTOR && !user.parent.user_type) {
        // 自己获取一级、二级的分佣
        balanceList.push({
        ...defaultParams,
          user_id: user.id,
          user_type: CommonUserLevelEnum.ONE_LEVEL_DISTRIBUTOR,
          amount: orderCode.rebate_price_agent,
          type: BalanceLogTypeEnum.DISTRIBUTOR_INCOME,
          description: `订单${orderCode.order_no}的一级分销商佣金【${orderCode.rebate_price_agent_percent}%】`
        })
        balanceList.push({
          ...defaultParams,
          user_id: user.id,
          user_type: CommonUserLevelEnum.ONE_LEVEL_DISTRIBUTOR,
          amount: orderCode.rebate_price_agent2,
          type: BalanceLogTypeEnum.DISTRIBUTOR_INCOME,
          description: `订单${orderCode.order_no}的二级分销商佣金【${orderCode.rebate_price_agent_percent2}%】`
        })
      } else if (user.user_type === CommonUserLevelEnum.SHOP_USER && !user.parent.user_type) {
        // 自己获取一级、二级的分佣
        balanceList.push({
          ...defaultParams,
          user_id: user.id,
          user_type: CommonUserLevelEnum.SHOP_USER,
          amount: orderCode.rebate_price_agent,
          type: BalanceLogTypeEnum.DISTRIBUTOR_INCOME,
          description: `订单${orderCode.order_no}的一级分销商佣金【${orderCode.rebate_price_agent_percent}%】`
        })
        balanceList.push({
         ...defaultParams,
          user_id: user.id,
          user_type: CommonUserLevelEnum.SHOP_USER,
          amount: orderCode.rebate_price_agent2,
          type: BalanceLogTypeEnum.DISTRIBUTOR_INCOME,
          description: `订单${orderCode.order_no}的二级分销商佣金【${orderCode.rebate_price_agent_percent2}%】`
        })
      }
    } else {
      // 平台直接获取
      balanceList.push({
        ...defaultParams,
        user_id: 1,
        user_type: CommonUserLevelEnum.ADMIN,
        amount: orderCode.rebate_price_agent,
        type: BalanceLogTypeEnum.DISTRIBUTOR_INCOME,
        description: `订单${orderCode.order_no}的一级分销商佣金【${orderCode.rebate_price_agent_percent}%】`
      })
      balanceList.push({
        ...defaultParams,
        user_id: 1,
        user_type: CommonUserLevelEnum.ADMIN,
        amount: orderCode.rebate_price_agent2,
        type: BalanceLogTypeEnum.DISTRIBUTOR_INCOME,
        description: `订单${orderCode.order_no}的二级分销商佣金【${orderCode.rebate_price_agent_percent2}%】`
      })
    }
    // 开始计算佣金插入佣金记录表以及用户更新剩余金额
    let userIdMap = {}
    // balanceList中的数据以user_id为key的形式存储对象
    console.log('balanceList',balanceList)
    for (let i = 0; i < balanceList.length; i++) {
      const item = balanceList[i]
      if (!userIdMap[item.user_id]) {
        userIdMap[item.user_id] = []
      }
      userIdMap[item.user_id].push(item)
    }
    for (const userId in userIdMap) {
      // 累加金额
      let amount = 0
      for (let i = 0; i < userIdMap[userId].length; i++) {
        amount += Number(userIdMap[userId][i].amount)
      }
      // 批量插入记录表
      await this.ctx.model.Business.BalanceRecord.bulkCreate(userIdMap[userId], {
        transaction
      })
      // 更新账户金额
      await this.ctx.model.Business.User.update({
        balance: this.ctx.model.Sequelize.literal(`balance + ${amount}`)
      }, {
        where: {
          id: userId
        },
        transaction
      })
    }
    return true
  }
  async verify(code, shop_user_id){
    // 创建事务
    const transaction = await this.app.model.transaction();
    try {
      // 1. 查找核销单
      const orderCode = await this.model.findOne({
        where: {
          code,
          shop_user_id,
          status: 0
        },
        transaction
      })
      if (!orderCode){
        throw new Error('核销码不存在或已被核销')
      }
      // 1. 更新所有id集合的状态为核销
      await this.model.update({
        status: 1,
        verify_time: new Date()
      }, {
        where: {
          id: orderCode.id,
        },
        transaction
      });
      // 分账
      await this.distribute({
        ...orderCode.dataValues,
        code_url: undefined,
        product_detail: undefined
      }, transaction)
      // 2. 查询该订单下是否还有待核销的数据
      let isExist = await this.model.findOne({
        where: {
          order_id: orderCode.order_id,
          status: 0
        },
        transaction
      });
      if (isExist){
         await transaction.commit();
         return true
      }
      // 3. 如果没有，则需要更新主订单状态
      await this.ctx.model.Business.Order.update({
        status: OrderStatusEnum.COMPLETED
      }, {
        where: {
          id: orderCode.order_id,
        },
        transaction
      })
      // 提交事务
      await transaction.commit();
    } catch (e) {
      // 打日志
      console.log(e)
      // 回滚事务
      await transaction.rollback();
      throw new Error(e)
    }
  }

  getPageInclude() {
    return [
      {
        model: this.ctx.model.Business.User,
        as: 'user',
      }
    ]
  }

  /**
   * 获取每日核销统计
   * @param {number} shop_user_id 商家用户ID 
   * @param {string} date 日期 YYYY-MM-DD
   */
  async getDailyStats(shop_user_id, date) {
    const startOfDay = new Date(date + ' 00:00:00');
    const endOfDay = new Date(date + ' 23:59:59');

    // 统计核销数量和总金额
    const result = await this.model.findOne({
      where: {
        shop_user_id: shop_user_id,
        status: 1, // 已核销
        verify_time: {
          [this.ctx.model.Sequelize.Op.gte]: startOfDay,
          [this.ctx.model.Sequelize.Op.lte]: endOfDay
        }
      },
      attributes: [
        [this.ctx.model.Sequelize.fn('COUNT', this.ctx.model.Sequelize.col('id')), 'checkCount'],
        [this.ctx.model.Sequelize.fn('SUM', this.ctx.model.Sequelize.col('product_price')), 'totalAmount']
      ],
      raw: true
    });

    return {
      checkCount: parseInt(result.checkCount) || 0,
      totalAmount: parseFloat(result.totalAmount) || 0
    };
  }
}

module.exports = OrderCodeService;
